from twisted.conch.telnet import TelnetTransport, Telnet
from twisted.internet.protocol import ClientFactory
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
import twisted.conch.telnet as telnet
#from twisted.protocols.basic import LineReceiver



class ConnectionStateProtocol(object):
    SerToCli = 1
    CliToServ = 0
    def __init__(self, State= SerToCli):
        self.CurrState = State
        
    def getCurrState(self):
        return self.CurrState
    
    def ChangeState(self):
        if self.CurrState == SerToCli:
            self.CurrState = CliToServ
        else:
            self.CurrState = SerToCli

class TelnetEngine(telnet.TelnetProtocol, ConnectionStateProtocol, ProtocolTransportMixin):
    LocalEnable = [telnet.ECHO, telnet.SGA, telnet.NAWS, telnet.NULL] #OPCION QUE SE REMUVA DE AQUI NO APARECERA EN US
#    LocalDisable = [AUTH]
    
    def __init__(self, State = ConnectionStateProtocol.SerToCli):
        ConnectionStateProtocol.__init__(self, State)
        
    def connectionMade(self):
        print "Connections :)"
        
    def dataReceived(self, data):
        print 'Recibimos algo'
        print data
    
    def telnet_DO(self, option):
        print 'en telnet do'
        self.protocol.telnet_DO(option)
        
    def enableLocal(self, option):
        self.protocol.enableLocal(telnet.ECHO)
    
    
class FactoryTelnetEngine(ClientFactory):
#    protocol = TelnetEngine
     
#    def buildProtocol(self, addr):
#        self.transport = telnet.TelnetTransport(TelnetEngine)
#        self.transport.factory = self
#        return self.transport

    def buildProtocol(self, addr):
        self.protocol = telnet.TelnetTransport(TelnetEngine)
        #self.transport = telnet.TelnetTransport(TelnetEngine)
        #self.protol = TelnetEngine()
        #self.protocol = telnet.TelnetTransport()
        self.factory = self
        return self.protocol
    
    def clientConnectionLost(self, conector, reason):
        print "Hemos perdido conexion con el cliente"

    
        
if __name__ == '__main__':
    from twisted.internet import reactor
    host = '192.168.213.143'
    port = 23
    factory = FactoryTelnetEngine()
    reactor.connectTCP(host, port, factory)
    print 'a correr'
    reactor.run()
    